package com.report.repository;

import com.report.entity.Report;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ReportRepository extends JpaRepository<Report, Object> {

    // 根据复合主键查询
    @Query("SELECT r FROM Report r WHERE r.bsdwxydm = :bsdwxydm AND r.reporttype = :reporttype AND r.mergeType = :mergeType")
    Optional<Report> findByBsdwxydmAndReporttypeAndMergeType(String bsdwxydm, String reporttype, Integer mergeType);

    // 自定义upsert方法
    default Report upsert(Report report) {
        Optional<Report> existing = findByBsdwxydmAndReporttypeAndMergeType(
                report.getBsdwxydm(),
                report.getReporttype(),
                report.getMergeType());

        if (existing.isPresent()) {
            Report toUpdate = existing.get();
            toUpdate.setReportinfo(report.getReportinfo());
            return save(toUpdate);
        } else {
            return save(report);
        }
    }

    @Query("SELECT p FROM Report p WHERE p.reporttype = :tname and p.bsdwxydm= :bsdwxydm and p.mergeType= :mergeType")
    Report getReport(String tname, String bsdwxydm, Integer mergeType);
}
